package controller.common;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import util.AliOssUtil;
import util.Result;

import java.io.IOException;
import java.util.UUID;

@MultipartConfig
@WebServlet("/upload")
public class AliOssUploadController extends HttpServlet {

    AliOssUtil aliOssUtil=new AliOssUtil();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            Part file=req.getPart("file");
            String originalFileName= file.getSubmittedFileName();
            int index=originalFileName.lastIndexOf(".");
            String extension=originalFileName.substring(index);
            //构建新文件名
            String objectName= UUID.randomUUID().toString()+extension;
            //文件请求路径
            String filePath= aliOssUtil.upload(file.getInputStream().readAllBytes(),objectName);
            resp.getWriter().write(filePath);
        } catch (IOException e) {
            Result.error("文件上传失败");
            System.out.println("文件上传失败："+e);
        }
    }
}
